/**
 * Copyright (C) 2009 Infinity Learning Solutions.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package twitter.service;

import java.util.*;

import net.oauth.*;
import net.oauth.client.*;
import net.oauth.client.httpclient3.*;

import twitter.model.*;

/**
 * @author Troy Tolle - DigitalChalk.com
 *
 */
public class TwitterHttpCommand {

	public enum HttpMethod {
		GET("GET"),
		POST("POST"),
		PUT("PUT"),
		DELETE("DELETE");
		
		private String value;
		private HttpMethod(String value) {
			this.value = value;
		}
		/**
		 * @see java.lang.Enum#toString()
		 */
		@Override
		public String toString() {
			return value;
		}
	}
	
	private TwitterConsumerCredentials credentials;
	
	/**
	 * 
	 */
	public TwitterHttpCommand(TwitterConsumerCredentials credentials) {
		assert null != credentials;
		this.credentials = credentials;
	}
	
	public TwitterHttpResponse execute(HttpMethod method, TwitterTokenPair access, String url, Map<String, String> parameters) throws TwitterOAuthException {
		TwitterHttpResponse result = null;
		
		OAuthAccessor oAuthAccessor = new OAuthAccessor(new OAuthConsumer(null, credentials.getKey(), credentials.getSecret(), null));
		OAuthClient oAuthClient = new OAuthClient(new HttpClient3());
		
		oAuthAccessor.accessToken = access.getToken();
		oAuthAccessor.tokenSecret = access.getTokenSecret();
		
		OAuthResponseMessage oAuthResponseMessage = null;
		try {
			oAuthResponseMessage = oAuthClient.access(oAuthAccessor.newRequestMessage(method.toString(), url, (null != parameters) ? parameters.entrySet() : null), ParameterStyle.AUTHORIZATION_HEADER);
			result = new TwitterHttpResponse();
			result.setStatus(oAuthResponseMessage.getHttpResponse().getStatusCode());
			result.setResponse(oAuthResponseMessage.getBodyAsStream());
			result.setResponseEncoding(oAuthResponseMessage.getBodyEncoding());
		} catch (Throwable t) {
			throw new TwitterOAuthException(t);
		}
		
		return result;
	}
}
